extends TextureButton

class_name ItemSlot

        
class ItemData:
    
    var ivt: Inventory
    var index: int

    func setup(ivt_: Inventory, index_: int) -> void:
        ivt = ivt_
        index = index_

@export var _item_texture_rect: TextureRect
@export var _item_count_lbl: Label

var item_data: ItemData = ItemData.new()
var item_texture: Texture2D:
    get:
        return _item_texture_rect.texture
    set(value):
        _item_texture_rect.texture = value

var item_count: int:
    get:
        return int(_item_count_lbl.text)
    set(value):
        _item_count_lbl.text = str(value)
        if value <= 0:
            _item_count_lbl.hide()
        else:
            _item_count_lbl.show()


func _init() -> void:
    toggle_mode = true


func _get_drag_data(_at_position: Vector2) -> Variant:
    if item_data.ivt.list[item_data.index] == null: return null
    var rect := TextureRect.new()
    rect.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
    rect.z_index = 99
    rect.texture = InventoryManager.get_item(item_data.ivt.list[item_data.index].id).icon
    set_drag_preview(rect)
    return item_data


func _can_drop_data(_at_position: Vector2, data: Variant) -> bool:
    return data is ItemData


func _drop_data(_at_position: Vector2, data: Variant) -> void:
    if data.ivt == item_data.ivt and data.index == item_data.index:
        return
    # 放下时，检查是否是相同的物品，以及是否可以叠加
    if item_data.ivt.list[item_data.index] != null:
        if item_data.ivt.list[item_data.index].id == data.ivt.list[data.index].id:
            var item := InventoryManager.get_item(item_data.ivt.list[item_data.index].id)
            if item.can_stacked:
                if data.ivt.list[data.index].count != item.max_stack_count and item_data.ivt.list[item_data.index].count != item.max_stack_count:
                    var c = InventoryManager.add_items_by_index(item_data.ivt, data.ivt.list[data.index].id, data.ivt.list[data.index].count, item_data.index)
                    InventoryManager.remove_items_by_index(data.ivt, data.index, data.ivt.list[data.index].count - c)
                    return
            else:
                return

    InventoryManager.swap_items(data.ivt, data.index, item_data.ivt, item_data.index)


